/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UserSelectionPanel.java
 *
 * Created on Apr 26, 2009, 8:27:11 PM
 */
package br.unisc.pdaapp.ui.messages;

import br.unisc.pdaapp.constants.IPanels;
import br.unisc.pdaapp.meta.ILoadableForm;
import br.unisc.pdaapp.meta.User;
import br.unisc.pdaapp.ui.CourseClasseslPanel;
import br.unisc.pdaapp.ui.MoodleMobileFrame;
import br.unisc.pdaapp.webservice.client.WSHandler;
import br.unisc.pdaapp.xml.MoodleXmlReader;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.JCheckBox;
import sun.misc.BASE64Decoder;

/**
 *
 * @author guilherme
 */
public class UserSelectionPanel extends javax.swing.JPanel implements ILoadableForm
{

    private static UserSelectionPanel instance;

    private Hashtable selectedUsers;

    /** Creates new form UserSelectionPanel */
    private UserSelectionPanel()
    {
        selectedUsers = new Hashtable();
        initComponents();
    }

    public static UserSelectionPanel getInstance()
    {
        if (instance == null)
        {
            instance = new UserSelectionPanel();
        }

        return instance;
    }

    public void loadForm()
    {
        usersListPanel.removeAll();
        selectedUsers.clear();

        WSHandler wsHandler = null;
        Vector usersList = null;

        try
        {
            wsHandler = new WSHandler();
            int courseID = CourseClasseslPanel.getInstance().getCourseID();
            byte[] result = wsHandler.getUsersByCourse(courseID);

            BASE64Decoder based = new BASE64Decoder();

            String encoded = new String(result);
            byte[] decoded = based.decodeBuffer(encoded);
            String xml = new String(decoded);
            System.out.println("xml: " + xml);

            MoodleXmlReader moodleXmlReader = new MoodleXmlReader();
            moodleXmlReader.readXML(xml, MoodleXmlReader.USERS, decoded);
            usersList = moodleXmlReader.getResultData();
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }

        if (usersList != null)
        {
            GridBagConstraints checkBoxGridBagConstraints = null;
            User loggedUser = MoodleMobileFrame.getInstance().getUser();

            for (int x = 0; x < usersList.size(); x++)
            {
                final User c = (User) usersList.get(x);

                //para não adicionar usuário logado.
                if (c.getUserName().equalsIgnoreCase(loggedUser.getUserName()))
                    continue;

                checkBoxGridBagConstraints = new GridBagConstraints();
                checkBoxGridBagConstraints.weightx = 1;
                checkBoxGridBagConstraints.weighty = ((x == usersList.size() - 1) ? 1 : 0);
                checkBoxGridBagConstraints.gridx = 1;
                checkBoxGridBagConstraints.gridy = x;
                checkBoxGridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
                checkBoxGridBagConstraints.insets = new Insets(2, 2, 0, 2);

                //inicializa com false.
                selectedUsers.put(c.getUserName(), String.valueOf(false));

                final JCheckBox checkbox = new JCheckBox(" " + c.getUserName());
                checkbox.setOpaque(false);
                checkbox.setFont(new java.awt.Font("Tahoma", 0, 10));
                checkbox.addItemListener(new ItemListener()
                {

                    public void itemStateChanged(ItemEvent e)
                    {
                        selectedUsers.put(c.getUserName(), String.valueOf(checkbox.isSelected()));
                    }
                });

                usersListPanel.add(checkbox, checkBoxGridBagConstraints);
            }
        }
    }

    public void setHeader(String text)
    {
    }

    /**
     * Seta como selecionado todos da lista.
     */
    private void selectAll()
    {
        Enumeration enumeration = selectedUsers.keys();
        int count = 0;
        
        while (enumeration.hasMoreElements())
        {
            JCheckBox checkBox = (JCheckBox) usersListPanel.getComponent(count);

            String userName = enumeration.nextElement().toString();
            selectedUsers.put(userName, String.valueOf(new Boolean(true)));

            //inverte a seleção
            checkBox.setSelected(true);
            count++;
        }
    }

    private String getSelectedUsers()
    {
        String selectedUsersS = "";
        Enumeration enumeration = selectedUsers.keys();

        while (enumeration.hasMoreElements())
        {
            String userName = enumeration.nextElement().toString();
            Boolean selected = Boolean.valueOf(selectedUsers.get(userName).toString());

            if (selected.booleanValue())
            {
                selectedUsersS += selectedUsersS.length() > 0 ? ";" + userName : userName;
            }
        }

        return selectedUsersS;
    }

    private void confirm()
    {
        MessagesSenderPanel.getInstance().setTargetUsers(getSelectedUsers());

        MoodleMobileFrame.getInstance().switchPanel(IPanels.MESSAGES_SENDER_PANE);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        backButton1 = new javax.swing.JButton();
        exitButton = new javax.swing.JButton();
        warningLabel = new javax.swing.JLabel();
        centerPanel = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        selectAllButton = new javax.swing.JButton();
        confirmButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        usersListPanel = new javax.swing.JPanel();

        setBackground(new java.awt.Color(255, 255, 255));
        setLayout(new java.awt.BorderLayout());

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setOpaque(false);
        jPanel1.setLayout(new java.awt.GridBagLayout());

        backButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/back.jpeg"))); // NOI18N
        backButton1.setBorder(null);
        backButton1.setOpaque(false);
        backButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                backButton1ActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 1);
        jPanel1.add(backButton1, gridBagConstraints);

        exitButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/close.jpeg"))); // NOI18N
        exitButton.setBorder(null);
        exitButton.setOpaque(false);
        exitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        jPanel1.add(exitButton, gridBagConstraints);

        warningLabel.setFont(new java.awt.Font("Tahoma", 2, 10));
        warningLabel.setForeground(new java.awt.Color(255, 0, 0));
        warningLabel.setText(" ");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        jPanel1.add(warningLabel, gridBagConstraints);

        add(jPanel1, java.awt.BorderLayout.NORTH);

        centerPanel.setBackground(new java.awt.Color(255, 255, 255));
        centerPanel.setLayout(new java.awt.BorderLayout());

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setOpaque(false);
        jPanel2.setLayout(new java.awt.GridBagLayout());

        selectAllButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/checkAll.jpeg"))); // NOI18N
        selectAllButton.setText("Todos");
        selectAllButton.setContentAreaFilled(false);
        selectAllButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectAllButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(1, 3, 1, 2);
        jPanel2.add(selectAllButton, gridBagConstraints);

        confirmButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/unisc/pdaapp/ui/images/success.png"))); // NOI18N
        confirmButton.setContentAreaFilled(false);
        confirmButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                confirmButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(1, 3, 1, 2);
        jPanel2.add(confirmButton, gridBagConstraints);

        centerPanel.add(jPanel2, java.awt.BorderLayout.NORTH);

        jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
        jScrollPane1.setOpaque(false);

        usersListPanel.setBackground(new java.awt.Color(255, 255, 255));
        usersListPanel.setLayout(new java.awt.GridBagLayout());
        jScrollPane1.setViewportView(usersListPanel);

        centerPanel.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        add(centerPanel, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void selectAllButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_selectAllButtonActionPerformed
    {//GEN-HEADEREND:event_selectAllButtonActionPerformed
        selectAll();
}//GEN-LAST:event_selectAllButtonActionPerformed

    private void confirmButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_confirmButtonActionPerformed
    {//GEN-HEADEREND:event_confirmButtonActionPerformed
        confirm();
}//GEN-LAST:event_confirmButtonActionPerformed

    private void backButton1ActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_backButton1ActionPerformed
    {//GEN-HEADEREND:event_backButton1ActionPerformed
        MoodleMobileFrame.getInstance().switchPanel(IPanels.MESSAGES_SENDER_PANE);
}//GEN-LAST:event_backButton1ActionPerformed

    private void exitButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_exitButtonActionPerformed
    {//GEN-HEADEREND:event_exitButtonActionPerformed
        MoodleMobileFrame.getInstance().quit(this);
}//GEN-LAST:event_exitButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backButton1;
    private javax.swing.JPanel centerPanel;
    private javax.swing.JButton confirmButton;
    private javax.swing.JButton exitButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton selectAllButton;
    private javax.swing.JPanel usersListPanel;
    private javax.swing.JLabel warningLabel;
    // End of variables declaration//GEN-END:variables

}
